<template>
	<div>
		  
			  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
			  <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad"
				:immediate-check="false">
				<van-checkbox-group v-model="checkedGroup" ref="checkboxGroup">
				   <van-card  :desc="item.description" :title="item.title" :thumb="item.cover" v-for="(item,index) in list" :key="index">
					<template #price>
					     <span style="color:red;font-size:14px;">{{item.price}}</span>
					</template>
					<template #thumb>
					        <!-- 自定义左侧部分，为了添加左侧checkbox -->
					        <div style="display: flex">
					          <van-checkbox
                              style="flex: 0.4"
                             :name="item.title+index"
                             checked-color="#b90505"
                             icon-size="12px"
                             @click="clickBox"></van-checkbox>
					          <van-image :src="item.cover" style="flex: 1.5" height="80px"></van-image>
					        </div>
					      </template>
						  
						  <template #title>
						         <!-- 自定义标题部分，主要是为了添加删除商品按钮 -->
						         <span style="font-size:14px;font-weight:600;">{{item.title}}</span>
						         <span style="float: right" @click="removeShop(item,index)"
						           ><van-icon name="delete" size="20"
						         /></span>
						       </template>
				   </van-card>
				    </van-checkbox-group>
			  </van-list>
			  </van-pull-refresh>
		     <div style="display:flex;align-items:center;justify-content:flex-end;width:100vw;line-height:20px;position:fixed;bottom:50px">
		       <div style="flex:1;margin-left:15px;">
		         <!-- 全选CheckBox部分 -->
		         <van-checkbox 
		           @click="checkAll"
		           v-model="isAllChecked"
		           checked-color="#b90505"
		           icon-size="12px"
		           >全选</van-checkbox
		         >
		       </div>
		       <div style="font-size: 14px;flex:2;">
		         <!-- 总价格部分 -->
		         总计：<span style="font-size: 16px; font-weight: 700;color:red">
				 {{"￥" + allcount}}
				 </span>
		       </div>
		       <div style="flex:1;">
		         <!-- 结算按钮 -->
		         <van-button  color="#b90505" style="border-radius:10px;" @click="jiesuan">结算</van-button>
		       </div>
		     </div>
		     <div style="height:50px;"></div>
		    <van-popup
		     v-model="showbuy"
		     position="bottom"
		     :style="{ height: '14%' }"
		     style="display:flex;align-items:center;justify-content: center;"
		   >
		     <van-list>
		       <van-cell @click="wxpay"><van-image
		           round
		           fit="cover"
		           width="20px"
		           height="20px"
		           style="pointer-events: none"
		           src="/image/weixinicon.jpg"
		         />&nbsp;微信支付</van-cell>
		       <!-- <van-cell @click="alipay"
		         >
				 <van-image
		           round
		           fit="cover"
		           width="20px"
		           height="20px"
		           style="pointer-events: none"
		           :src="$front.dir + 'image/my/alipayicon.jpg'"
		         />
				 &nbsp;支付宝支付</van-cell
		       > -->
		     </van-list>
		   </van-popup>   
		   <xjmenubar :menubar="tabbar" :prevent="false" :cactive="cactive"></xjmenubar>
	</div>
</template>

<script>
	import xjmenubar from '@/components/shop/xjmenubar.vue';
	export default{
		components: {
			xjmenubar
		},
		data(){
			return{
				checkedGroup:[],
				showbuy:false,
				totalprice:0,
				tabbar:"",
				cactive:2,
				list:[],
				shoplist:[],
				loading: true,
				finished: false,
				refreshing: false,
				page: 1, //第1页数据
				total: '',
				isAllChecked:false
			}
		},
		methods: {
			async getPhonePageData() {
				let res = await this.$frontaxios.post(this.$front.getPhonePageData);
				//console.log(res);
				if (!res.data) {
					this.$notify({ type: 'warning', message:'请设置店铺首页，再过来查看' });
					return;
				}
				if (res.code == 1) {
					this.tabbar = res.data.tabbar;
				} else {
					this.$notify({ type: 'warning', message:res.msg});
				}
			},
		    async getShopCart() {
				let query = {
					orderstatus: 0,
					page: this.page,
					limit: 10
				}
		       let res = await this.$frontaxios.post(this.$front.getShopCart,query);
			   if(res.code==1){
                  this.shoplist=res.data.list;
				  this.total=res.data.total;
			   }
		    },
			async onLoad() {
				if (this.refreshing) {
					this.list = [];
					this.refreshing = false;
				}
				await this.getShopCart();
				this.list.push(...this.shoplist);
				this.page++;
				this.loading = false;
				if (this.list.length >= this.total) {
					this.finished = true;
				}
			},
			onRefresh() {
				// 清空列表数据
				this.finished = false;

				// 重新加载数据
				// 将 loading 设置为 true，表示处于加载状态
				this.loading = true;
				this.page = 1;
				this.onLoad();
				this.$toast.success("刷新成功");
			},
		    checkAll() {
		      if (this.checkedGroup.length !== 0) {
		        //有商品卡片选中
		        if (this.checkedGroup.length === this.list.length) {
		          //总商品数与选中商品卡片数相等，说明此时已全选
		          this.$refs.checkboxGroup.toggleAll(false); //令所有选中的反选，即全不选
				  this.isAllChecked=false;
		        } else {
		          //商品卡片数部分选中
		          this.$refs.checkboxGroup.toggleAll(true); //令所有商品全部选中
				  this.isAllChecked=true;
		        }
		      } else {
		        //没有商品卡片选中，直接全选
		        this.$refs.checkboxGroup.toggleAll(true);
				this.isAllChecked=true;
		      }
		    },
			clickBox(){
				if(this.checkedGroup.length === this.list.length){
					this.isAllChecked=true;
				}else{
					this.isAllChecked=false;
				}
			},
		    addnum(item,index) {
		      this.list[index].num = parseInt(item.num) + 1;
		    },
		    minusnum(item,index) {
		      this.list[index].num = parseInt(item.num) - 1;//(element => { return element.title === item.title})
		    },
			//点击删除按钮触发的函数
		    removeShop(item,index) { 
			this.$dialog.confirm({
			  title: '提醒',
			  message: '确认删除吗',
			})
			  .then(async () => {
			   let res=await this.$frontaxios.post(this.$front.removeShop,{id:item.id});
			   if(res.code==1){
				   this.$toast.success('商品移除成功');
				   this.list.splice(index, 1); //移除商品 let index = this.checkedGroup.indexOf(item.title);
			       this.checkedGroup.splice(index, 1); //移除checkedGroup中刚刚删除的商品，不然不会即时刷新
			   }else{
				   this.$toast.fail('商品移除失败');
			   }
			
			  })
			  .catch(() => {
			    // on cancel
			  });
			    },
			  
		  jiesuan:function(){
		     if(this.checkedGroup.length==0){
		          return;
		     }
		     this.showbuy = true;
		  },
		  wxpay:function(){
		     var arr=[];
		    for(let i=0;i<this.list.length;i++){
		     if(this.checkedGroup.find(item => { //判断是否选中商品，未选中不计算在内
		           return item === this.list[i].title+i;
		                })){
		         let params={
		           columnid:this.list[i].columnid,
				   knowledgeid:this.list[i].knowledgeid,
				   title:this.list[i].title,
				   cover:this.list[i].cover,
				   description:this.list[i].description,
				   price:this.list[i].price,
		           totalprice:this.totalprice
		         };
		         arr.push(params);
		        }
		     }
		    //  this.$router.push({
		    //     name: "ordermore",
		    //     params: {
		    //       shopinfo: JSON.stringify(arr),
		    //     },
		    //   });
			let domainname = this.$route.params.domainname;
            let FrontUrl = window.location.protocol + '//' + window.location.host;
            const nexturl = FrontUrl + `/xuejing/ordermore/${domainname}?shopinfo=${encodeURIComponent(JSON.stringify(arr))}`; //跳转到下一个页面的地址http://192.168.2.11/#/xuejing/order/test1?id=8
            let url = this.$front.getWeiXinOpenId + `?nexturl=${encodeURIComponent(nexturl)}`; //请求获得openid并存入到服务器的Cache当中
            //console.log(url);return;
			window.location.href = url;
		  }
		  },
		  computed: {
		     allcount(){
		            let sumup = 0
		            for(let i=0;i<this.list.length;i++){
		                if(this.checkedGroup.find(item => { //判断是否选中商品，未选中不计算在内
		                    return item === this.list[i].title+i;
		                })){
		                    sumup += this.list[i].num*this.list[i].price;//this.list[i].num
		                }else{
		                    continue;
		                }
		            }
		            return this.totalprice=sumup;
		        }
		  },created(){
			  this.getPhonePageData();
			  this.onLoad();
		  }
	}
</script>

<style>
</style>